package com.ntschy.common.utils.file;

import com.ntschy.common.config.ProjectConfig;
import com.ntschy.common.constant.HttpStatus;
import com.ntschy.common.exception.file.FileException;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;

import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author ezreal_geng
 */
public class FileUtil {

    public static Resource loadFileAsResource(String path) {
        Path file = Paths.get(ProjectConfig.getUpload() + path).toAbsolutePath().normalize();
        //Path path = Paths.get(filePath).toAbsolutePath().normalize().resolve(fileName).normalize();
        try {
            UrlResource resource = new UrlResource(file.toUri());
            if (resource.exists()) {
                return resource;
            }
            throw new FileException(HttpStatus.FILE, "文件不存在");
        }
        catch (MalformedURLException e) {
            throw new FileException(HttpStatus.FILE, "文件不存在");
        }
    }
}
